<template>
  <div class="ele-body">
    <el-card shadow="never">
      <div slot="header" class="clearfix">
        <span>小红书账户管理</span>
      </div>
      <!-- 搜索表单 -->
      <el-form
        :model="where"
        class="ele-form-search"
        label-width="75px"
        @keyup.enter.native="reload"
        @submit.native.prevent
      >
        <div class="app-container">
          <div class="filter-container">
            <el-select
              v-model="where.bazaarId"
              class="filter-item"
              clearable
              placeholder="推广市场"
              style="width: 180px"
              @change="reload"
            >
              <el-option
                v-for="item in BazaarList"
                :key="item.id"
                :disabled="item.status === 0"
                :label="item.name"
                :value="item.id"
              />
            </el-select>

            <el-input
              v-model="where.username"
              class="filter-item"
              clearable
              placeholder="推广账户"
              style="width: 180px"
              @clear="reload"
            />

            <el-select
              v-model="where.userStat"
              class="filter-item"
              clearable
              placeholder="推广账户状态"
              style="width: 160px"
              @change="reload"
              @clear="reload"
            >
              <el-option
                v-for="item in userStatList"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>

            <el-button
              class="filter-item"
              icon="el-icon-search"
              type="primary"
              @click="reload"
              >搜索
            </el-button>

            <el-button
              class="filter-item"
              icon="el-icon-refresh"
              style="margin-left: 2px"
              @click="reset"
              >重置
            </el-button>
          </div>
        </div>
      </el-form>

      <!-- 数据表格 -->
      <ele-pro-table
        ref="table"
        :columns="columns"
        :datasource="url"
        :max-height="defaultHeight"
        :parse-data="parseData"
        :selection.sync="selection"
        :where="where"
      >
        <!-- 表头工具栏 -->
        <template slot="toolbar">
          <el-button
            v-if="$hasPermission('xhs:save')"
            icon="el-icon-plus"
            plain
            size="small"
            type="primary"
            @click="openEdit({})"
            >添加账户
          </el-button>
          <el-button
            v-if="$hasPermission('xhs:delete')"
            :disabled="selection.length === 0"
            icon="el-icon-delete"
            plain
            size="small"
            type="danger"
            @click="removeBatch"
            >删除账户
          </el-button>
          <el-button
            v-if="$hasPermission('xhs:update')"
            :disabled="selection.length === 0"
            icon="el-icon-refresh-right"
            plain
            size="small"
            type="success"
            @click="refreshBatch"
            >获取最新数据
          </el-button>
        </template>

        <!-- 推广市场列 -->
        <template slot="bazaarId" slot-scope="{ row }">
          <template v-for="item in BazaarList">
            <span v-if="row.bazaarId === item.id" :key="item.id">
              {{ item.name }}
            </span>
          </template>
        </template>

        <!-- 推广状态列 -->
        <template slot="userStat" slot-scope="{ row }">
          <span v-if="row.userStat === 1">账户正常</span>
          <span v-if="row.userStat === 2" style="color: red"
            >登录凭证已失效</span
          >
        </template>

        <!-- 状态列 -->
        <template slot="status" slot-scope="{ row }">
          <el-switch
            v-model="row.status"
            :active-value="1"
            :inactive-value="0"
            @change="editState(row)"
          />
        </template>

        <!-- 最后刷新时间列 -->
        <template slot="lastDatetime" slot-scope="{ row }">
          <span>
            <i class="el-icon-time"></i>
            {{ formatTime(row.lastDatetime) }}
          </span>
        </template>

        <!-- 操作列 -->
        <template slot="action" slot-scope="{ row }">
          <el-link
            v-if="$hasPermission('xhs:update')"
            :underline="false"
            icon="el-icon-edit-outline"
            type="primary"
            @click="openEdit(row)"
            >更新
          </el-link>
          <el-popconfirm
            class="ele-action"
            title="确定要删除此用户吗？"
            @confirm="remove(row)"
          >
            <el-link
              v-if="$hasPermission('xhs:delete')"
              slot="reference"
              :underline="false"
              icon="el-icon-delete"
              type="danger"
              >删除
            </el-link>
          </el-popconfirm>
        </template>
      </ele-pro-table>
    </el-card>

    <!-- 编辑弹窗 -->
    <vue-edit :data="current" :visible.sync="showEdit" @done="reload" />
  </div>
</template>

<script>
import VueEdit from "./vue-edit";

export default {
  name: "xhsAccount",
  components: { VueEdit },
  data() {
    return {
      //市场列表
      BazaarList: [],
      // 表格高度
      defaultHeight: 0,
      // 推广账户状态
      userStatList: [
        { value: 1, label: "账户正常" },
        { value: 2, label: "登录凭证已失效" },
      ],
      // 表格数据接口
      url: "/Xhs/read",
      // 表格列配置
      columns: [
        {
          columnKey: "selection",
          type: "selection",
          width: 45,
          align: "center",
        },
        {
          prop: "username",
          label: "推广账户",
          sortable: "custom",
          showOverflowTooltip: true,
        },
        {
          prop: "bazaarId",
          label: "推广市场",
          slot: "bazaarId",
          sortable: "custom",
          showOverflowTooltip: true,
        },
        {
          prop: "balance",
          label: "账户余额",
          sortable: "custom",
          showOverflowTooltip: true,
        },
        {
          prop: "cost",
          label: "今日消费",
          sortable: "custom",
          showOverflowTooltip: true,
        },
        {
          prop: "budget",
          label: "账户日预算",
          sortable: "custom",
          showOverflowTooltip: true,
        },
        {
          prop: "userStat",
          label: "接口状态",
          sortable: "custom",
          showOverflowTooltip: true,
          slot: "userStat",
        },
        {
          prop: "lastDatetime",
          label: "同步时间",
          sortable: "custom",
          resizable: false,
          slot: "lastDatetime",
        },
        {
          prop: "status",
          label: "账户状态",
          sortable: "custom",
          resizable: false,
          slot: "status",
        },
        {
          columnKey: "action",
          label: "操作",
          width: 130,
          resizable: false,
          slot: "action",
        },
      ],
      // 表格搜索条件
      where: {},
      // 是否显示编辑弹窗
      showEdit: false,
      // 表格选中数据
      selection: [],
      // 当前编辑数据
      current: null,
    };
  },
  created() {
    window.addEventListener("resize", this.getHeight);
    this.getHeight();
  },

  methods: {
    /*设置表格高度*/
    getHeight() {
      this.defaultHeight = window.innerHeight - 360;
    },

    /*表格数据加载*/
    parseData(res) {
      if (res.code === 0) {
        this.BazaarList = res.bazaar;
      }
      return {
        code: res.code,
        data: res.data,
        count: res.count,
        msg: res.msg,
      };
    },

    /* 刷新表格 */
    reload(isPage) {
      let obj = { where: this.where };
      if (!isPage) {
        obj.page = 1;
      }
      this.$refs.table.reload(obj);
    },

    /* 重置搜索 */
    reset() {
      for (let key in this.where) {
        this.where[key] = null;
      }
      this.reload();
    },

    /*批量刷新*/
    refreshBatch() {
      if (!this.selection.length) {
        this.$message.error("请至少选择一条数据");
        return;
      }
      this.$confirm("确定要同步选中的用户数据吗?", "提示", {
        confirmButtonText: "更新",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          let requestArray = [];
          const selectionArray = this.selection.map((d) => d.id);
          const loading = this.$loading({ lock: true });
          selectionArray.forEach((item) => {
            requestArray.push(
              this.$http.put("/xhs/updateUser", {
                id: item,
              })
            );
          });
          Promise.all(requestArray)
            .then(() => {
              loading.close();
              this.reload();
            })
            .catch((e) => {
              this.$message.error(e.message);
              loading.close();
            });
        })
        .catch(() => {});
    },

    /* 显示编辑 */
    openEdit(row) {
      row.bazaar = this.BazaarList;
      this.current = row;
      this.showEdit = true;
    },

    /* 删除 */
    remove(row) {
      const loading = this.$loading({ lock: true });
      this.$http
        .delete("/Xhs/delete/id/" + row.id)
        .then((res) => {
          loading.close();
          if (res.data.code === 0) {
            this.$message.success(res.data.msg);
            this.reload();
          } else {
            this.$message.error(res.data.msg);
          }
        })
        .catch((e) => {
          loading.close();
          this.$message.error(e.message);
        });
    },

    /* 批量删除 */
    removeBatch() {
      if (!this.selection.length) {
        this.$message.error("请至少选择一条数据");
        return;
      }
      this.$confirm("确定要删除选中的用户吗?", "提示", {
        confirmButtonText: "删除",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          const iad = this.selection.map((d) => d.id);
          const loading = this.$loading({ lock: true });
          this.$http
            .delete("/Xhs/delete", {
              data: { id: iad.join(",") },
            })
            .then((res) => {
              loading.close();
              if (res.data.code === 0) {
                this.$message({ type: "success", message: res.data.msg });
                this.reload();
              } else {
                this.$message.error(res.data.msg);
              }
            })
            .catch((e) => {
              loading.close();
              this.$message.error(e.message);
            });
        })
        .catch(() => {});
    },
    /* 更改状态 */
    editState(row) {
      const loading = this.$loading({ lock: true });
      this.$http
        .put("/Xhs/update/state/" + row.id, { status: row.status })
        .then((res) => {
          loading.close();
          if (res.data.code === 0) {
            this.$message({ type: "success", message: res.data.msg });
          } else {
            row.state = !row.state ? 1 : 0;
            this.$message.error(res.data.msg);
          }
        })
        .catch((e) => {
          loading.close();
          this.$message.error(e.message);
        });
    },
    /*时间格式化*/
    formatTime(value) {
      const stamp = new Date().getTime() - new Date(value).getTime();
      if (stamp >= 1000 * 60 * 60 * 24) {
        return ((stamp / 1000 / 60 / 60 / 24) | 0) + "天前";
      } else if (stamp >= 1000 * 60 * 60) {
        return ((stamp / 1000 / 60 / 60) | 0) + "小时前";
      } else if (stamp >= 60000) {
        //1分钟以内为：刚刚
        return ((stamp / 1000 / 60) | 0) + "分钟前";
      }
      return "刚刚";
    },
  },
};
</script>

<style scoped>
.ele-table-tool .is-disabled {
  cursor: not-allowed;
  filter: Alpha(opacity=0.65);
  -moz-opacity: 0.65;
  opacity: 0.65;
}
</style>
